-- 动态修改 iptables 规则
function add_rule(ip)
    -- 检查规则是否已经存在
    local check_command = string.format("iptables -C FORWARD -p tcp -s %s -j ACCEPT", ip)
    local exists = os.execute(check_command) == 0
    
    if not exists then
        -- 如果规则不存在，则添加规则
        local command = string.format("iptables -I FORWARD -p tcp -s %s -j ACCEPT", ip)
        os.execute(command)
        print("Added rule for IP: " .. ip)
    else
        print("Rule for IP: " .. ip .. " already exists.")
    end
end

-- 删除 iptables 规则
function delete_rule(ip)
    -- 检查规则是否已经存在
    local check_command = string.format("iptables -C FORWARD -p tcp -s %s -j ACCEPT", ip)
    local exists = os.execute(check_command) == 0
    
    if exists then
        -- 如果规则存在，则删除规则
        local command = string.format("iptables -D FORWARD -p tcp -s %s -j ACCEPT", ip)
        os.execute(command)
        print("Deleted rule for IP: " .. ip)
    else
        print("Rule for IP: " .. ip .. " does not exist.")
    end
end

-- 解析 tcpdump 输出
function process_packet(packet)
    -- 提取源 IP 和响应码
    local src_ip, dest_ip, response_code = string.match(packet, "IP (%d+%.%d+%.%d+%.%d+)%.%d+ > (%d+%.%d+%.%d+%.%d+)%.%d+:.-HTTP/1.%d (%d+)")
	print(dest_ip)
	print(response_code)
    -- 检查是否匹配
    if dest_ip and response_code then
        if response_code == "302" then
            -- 响应码 302，删除允许通过
			delete_rule(dest_ip)
        elseif response_code == "204" then
            -- 响应码 204，允许通过规则
            add_rule(dest_ip)
        end
    end
end

-- 启动 tcpdump 命令并实时处理
function start_tcpdump()
    local command = "tcpdump -i br-lan -nn tcp src port 80 and src host 192.168.1.195 -l"
    local file = io.popen(command)  -- 打开tcpdump输出
    while true do
        local packet = file:read("*l")  -- 持续读取每一行数据包
        if packet then
            process_packet(packet)  -- 处理每个数据包
        else
            break
        end
    end
end

-- 启动 tcpdump 监听
start_tcpdump()
